import React, { useState, useEffect, useMemo } from 'react';
import Head from 'next/head';
import {
  Row,
  Col,
  Tag,
  Input,
  Avatar,
  Button,
  List,
  message,
  Modal,
} from 'antd';
const { TextArea } = Input;
import { QqOutlined, FormOutlined, UserOutlined } from '@ant-design/icons';
import Header from '../components/header';
import Footer from '../components/footer';
import Bgc from '../components/bgc';
import cssInteract from '../static/style/pages/interact.scss';
import API from '../util/apiUrl';
import { dateFormat } from '../util/data';

const avatarList = [
  '../static/img/avatar/1.jpg',
  '../static/img/avatar/2.jpg',
  '../static/img/avatar/3.jpg',
  '../static/img/avatar/4.jpg',
  '../static/img/avatar/5.jpg',
  '../static/img/avatar/6.jpg',
];

const Interact = (props) => {
  // console.log('Interact props', props, 'cssInteract', cssInteract);
  let avatarYs = props.list[0].mydetailsRes[0].avatar.split('.');
  avatarYs[avatarYs.length - 2] += 'ys';
  avatarYs = avatarYs.join('.');
  const myDetails = { ...props.list[0].mydetailsRes[0], avatar: avatarYs };
  console.log('props.list[1].boardRes', props.list[1].boardRes);
  const [boardList, setBoardList] = useState(props.list[1].boardRes);
  const [bgcUrl, setBgcUrl] = useState({});
  const [showModal, setShowModal] = useState(false);
  const [input, setInput] = useState(null);
  // 回复的对象名
  const [replyName, setReplyName] = useState('');
  // 回复的对象id
  const [boardId, setBoardId] = useState('');
  const [btnDisabled, setBtnDisabled] = useState(false);
  const [boardApi, setBoardApi] = useState('sendMessage');
  // const [isLoading, setIsLoading] = useState(false);
  useEffect(() => {
    showTop();
  }, []);
  const tagsColor = ['blue', 'geekblue', 'purple', 'lime', 'green', 'cyan'];

  // 直接显示顶部
  const showTop = () => {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  };

  // 滚动到文章位置
  const scrollTo = (id) => {
    let domY =
      document.getElementById(id).getBoundingClientRect().top -
      55 +
      window.pageYOffset;
    window.scrollTo({
      top: domY,
      behavior: 'smooth', //  smooth(平滑滚动),instant(瞬间滚动),默认auto
    });
  };

  // 发送
  const sendMessage = () => {
    if (!input.state.value.trim()) return false;
    // 弹出框
    setShowModal(true);
  };

  const handleOk = () => {
    console.log('发送', input.state.value.trim());
    let isLogin = false; //TODO:没有登陆
    // 如果没有登陆,拿本机的游客名称和头像
    let touristInfo = JSON.parse(window.localStorage.getItem('touristInfo'));

    let num = Math.floor(Math.random() * (5 - 0 + 1) + 0);
    console.log('num', num);
    let name, avatar;
    if (isLogin) {
      //name是登陆拿到的名称,头像
    } else if (touristInfo) {
      name = touristInfo.name;
      avatar = touristInfo.avatar;
    } else {
      let strNum = new Date().getTime() + '';
      name = '游客' + strNum.substr(strNum.length - 6);
      avatar = avatarList[num]; //没登录的默认头像
    }
    let data = {
      avatar,
      name,
      content: input.state.value.trim(),
      updateTime: dateFormat('YYYY-mm-dd HH:MM:SS', new Date()),
      isLogin: isLogin ? '1' : '0',
      replyName,
      boardId,
    };
    setBtnDisabled(true);
    API[boardApi](data)
      .then((res) => {
        console.log('res', res);
        if (res.data.isScuccess) {
          // 添加成功
          // 清除表单
          console.log('input', input);
          input.state.value = '';
          // 游客名称和头像加入储存
          if (!isLogin) {
            window.localStorage.setItem(
              'touristInfo',
              JSON.stringify({ name, avatar })
            );
          }
          message.success('留言成功');
          setBtnDisabled(false);
          // 动态渲染
          setBoardList([data].concat(boardList));

          //TODO:回复成功后还要展示+定位  进入页面还要获取数据,左右外连接
        }
      })
      .catch((err) => {
        message.warning('留言失败');
        setBtnDisabled(false);
        console.log('err', err);
      });

    // 关闭弹窗
    setShowModal(false);
    setBoardApi('sendMessage');
    setReplyName('');
  };
  const handleCancel = () => {
    setShowModal(false);
  };

  const reply = (item) => {
    console.log('回复', item);
    input.focus();
    setReplyName(item.name);
    setBoardId(item.id);
    setBoardApi('replyMessage');
    scrollTo('boardListTitle');
  };

  return (
    <>
      <Modal
        title="提示"
        visible={showModal}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>尚未进行登录授权, 是否以游客身份留言?</p>
      </Modal>

      <Head>
        <title>yzyの博客-互动</title>
        <link
          rel="shortcut icon"
          href="../static/img/bitbug_favicon.ico"
          type="image/x-icon"
        />
      </Head>

      <Header
        getBgcUrl={(data) => {
          setBgcUrl(data);
        }}
        current="4"
      />

      <Bgc
        bgcUrl={bgcUrl}
        scrollTo={(id) => {
          scrollTo(id);
        }}
        btns={[
          {
            name: '博主信息',
            id: 'bloggerInfo',
            icon: 'icon-usercenter',
          },
          {
            name: '留言板',
            id: 'boardListTitle',
            icon: 'icon-suggest',
          },
        ]}
      />
      {/* <div
        className={cssInteract.bgcImg}
        // style={{ backgroundImage: `url(${bgcUrl.carousel_img})` }}
      >
        <div className={cssInteract.content}>
          <div className={cssInteract.title}>
            <h3>{bgcUrl.name}</h3>
            <span>一些文字..</span>
          </div>
        </div>
      </div> */}

      <div className={cssInteract.common}>
        <Row className={cssInteract.comm_main} justify="center">
          <Col className={cssInteract.comm_home} span={24}>
            <div className={cssInteract.content}>
              <Avatar
                id="bloggerInfo"
                className={cssInteract.avatar}
                size={120}
                style={{
                  backgroundImage: `url('${myDetails.avatar || null}')`,
                }}
                icon={myDetails.avatar ? null : <UserOutlined />}
              />
              <div className={cssInteract.msg}>
                <p className={cssInteract.name}>{myDetails.name}</p>
                <p className={cssInteract.skillType}>{myDetails.skillType}</p>
                <p className={cssInteract.synopsis}>{myDetails.synopsis}</p>
                <p className={cssInteract.tags}>
                  {myDetails.tags
                    ? myDetails.tags.split(',').map((i, idx) => (
                        <Tag
                          className={cssInteract.tag}
                          key={idx}
                          color={tagsColor[idx % 6]}
                        >
                          {i}
                        </Tag>
                      ))
                    : null}
                </p>
              </div>
            </div>
          </Col>
        </Row>
      </div>

      <div className={cssInteract.board}>
        <Row className={cssInteract.board_main} justify="center">
          <Col className={cssInteract.board_home} span={24}>
            <div className={cssInteract.content} id="boardListTitle">
              <p className={cssInteract.title}>
                <FormOutlined />
                &nbsp;留言板
                <span className={cssInteract.num}>
                  <i>{boardList.length}</i> 条评论
                </span>
              </p>
              <div className={cssInteract.board}>
                <p className={cssInteract.hint}>
                  在这里可以留下你的足迹，欢迎在下方留言，欢迎指出错误和不足，一起交流学习！
                </p>
                <div className={cssInteract.speak}>
                  {replyName && (
                    <div>
                      <span style={{ marginLeft: 80,cursor:'pointer'}} onClick={()=>{
                        setReplyName('')
                      }}>X</span>
                      <span style={{ marginLeft: 30, color: '#1abc9c' }}>
                        回复 : {replyName}
                      </span>
                    </div>
                  )}

                  <div className={cssInteract.input}>
                    <Avatar
                      className={cssInteract.avatar}
                      size={60}
                      icon={<QqOutlined />}
                    />
                    <TextArea
                      // value={value}
                      ref={(e) => {
                        setInput(e);
                      }}
                      placeholder="请输入内容"
                      autoSize={{ minRows: 3, maxRows: 5 }}
                    />
                  </div>
                  <div className={cssInteract.btn}>
                    <Button
                      onClick={() => {
                        console.log('登陆');
                        message.warning('还在开发中');
                      }}
                      type="ghost"
                    >
                      QQ登陆
                    </Button>{' '}
                    &nbsp;
                    <Button
                      onClick={sendMessage}
                      disabled={btnDisabled}
                      type="primary"
                    >
                      发送
                    </Button>
                  </div>
                </div>
                <div className={cssInteract.boardList}>
                  <List
                    itemLayout="horizontal"
                    dataSource={boardList}
                    renderItem={(item) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={
                            <Avatar
                              src={item.avatar}
                              icon={item.avatar ? null : <QqOutlined />}
                            />
                          }
                          title={
                            <>
                              <span className={cssInteract.name}>
                                {item.name}
                              </span>
                              <br />
                              <span className={cssInteract.time}>
                                {item.updateTime}
                              </span>
                            </>
                          }
                          description={
                            <div className={cssInteract.content}>
                              <div>{item.content}</div>
                              <p className={cssInteract.reply}>
                                <span
                                  style={{ cursor: 'pointer' }}
                                  onClick={() => {
                                    reply(item);
                                  }}
                                >
                                  回复
                                </span>
                              </p>
                            </div>
                          }
                        />
                      </List.Item>
                    )}
                  />
                </div>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <Footer />
    </>
  );
};

Interact.getInitialProps = async () => {
  let res = await API.getInteract();
  // console.log('res000', res);
  return { list: res.data };
};

export default Interact;
